/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zhihuitong.meeting.net.callback;

import android.app.Activity;
import android.content.DialogInterface;
import android.view.KeyEvent;

import com.lzy.okgo.request.base.Request;
import com.zhihuitong.meeting.net.HttpUtil;
import com.zhihuitong.meeting.view.CustomDialog;

import okhttp3.Response;

/**
 * 作者: 123
 * 日期: 2017/6/12
 * 描述:对于网络请求是否需要弹出进度对话框
 */

public abstract class DialogCallback<T> extends MyCallBack<T> {

    private CustomDialog dialog;

    private void initDialog(Activity activity, final Object tag) {
        dialog = new CustomDialog(activity);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0) {
                    if (tag != null) {
                        HttpUtil.cancelTag(tag);
                    }
                    dialog.dismiss();
                }
                return false;
            }
        });
    }

    /**
     * 带对话框的callBack
     *
     * @param activity
     * @param tag      取消网络请求的tag,传请求的接口地址
     */
    public DialogCallback(Activity activity, Object tag) {
        super();
        initDialog(activity, tag);
    }

    public DialogCallback(Activity activity) {
        super();
        initDialog(activity, null);
    }

    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onFinish() {
        //网络请求结束后关闭对话框
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public T convertResponse(Response response) throws Throwable {
        return super.convertResponse(response);
    }
}
